#!/usr/bin/ruby

# TODO:
# 1. call event handler to save the data into the database
# 1.(option 2) create a pipeline of processes

require 'pp'
require 'yaml'

def skip_line(filters, line)
    skip = false
    filters.each do |f|
                if line =~ /#{f}/ 
                    skip = true
                    break
                end                            
    end if filters
    return skip   
end

def save_instance_event(line)
    line =~ /\[((\d|\s|\:)*)\]\s\[(\w|\W)*\](\s)+INFO(\s)*(\w-(\d|\w)+)\sstate\schange:\s((\w)+)\s->\s((\w)+)/
    pp "Time: #{$1}, Instance: #{$6}, From State: #{$8}, To:#{$10}"
end

cfg = YAML::load_file('parser_cfg.yml')

cfg.each_pair do |k,v|
    file_pattern = k
    next if v[:ignore.to_s] # do not process this file set if ignore flag is set to true
    parse_exp = v[:parse_exp.to_s]
    filters = v[:filters.to_s]
    event_handler = v[:event_handler.to_s]
    
    Dir.glob(file_pattern).each do |filename|
        line_number = 0
        pp "Processing #{filename} with pattern #{parse_exp} excluding filters: #{filters.join('----') if filters}"
        IO.foreach(filename, "\n") do |line|
            line_number += 1
            next unless line =~ /#{parse_exp}/ 
            next if skip_line(filters, line)
            pp "#{line_number} : #{line}"
            eval("#{event_handler}('#{line}')") if event_handler
        end
    end
end
